import queue
import threading
import servletapi

class RequestQueue(threading.Thread):
    requests = queue.Queue() # 等待签到的队列
    messages = queue.Queue() # 输出消息队列
    present_list = set() # 已经签到的名单
    password = "" # 签到口令
    
    def set_password(self, password):
        self.password = password

    def add_checkin_request(self, sid):
        self.requests.put(sid)

    def get_next_message(self):
        msg = self.messages.get()
        self.messages.task_done()
        return msg

    def run(self):
        while True:
            sid = self.requests.get()
            self.requests.task_done()
            if sid not in self.present_list:
                try:
                    resp = servletapi.checkin(sid, self.password)
                    if resp[0] == "ok":
                        self.present_list.add(sid)
                        self.messages.put("{}签到成功".format(sid))
                    elif resp[0] == "late":
                        self.present_list.add(sid)
                        self.messages.put("{}已迟到".format(sid))
                    elif resp[0] == "end":
                        self.messages.put("签到已经截止")
                        self.present_list.add(sid)
                    elif resp[0] == "out":
                        self.messages.put("{}不在选课列表".format(sid))
                        self.present_list.add(sid)
                    elif resp[0] == "wrong_passwd":
                        self.messages.put("请考勤助理注意，签到口令错误")
                    elif resp[0] == "too_early":
                        self.messages.put("签到尚未开始")
                    elif resp[0] != "checked_in":
                        self.messages.put("错误{}".format(resp[0]))
                except Exception as ex:
                    self.messages.put("错误{}".format(ex))
